package zd.cornermemory.ui;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.pgyer.pgyersdk.PgyerSDKManager;
import com.pgyer.pgyersdk.callback.CheckoutCallBack;
import com.pgyer.pgyersdk.model.CheckSoftModel;

import zd.cornermemory.R;
import zd.cornermemory.fragment.DisruptFragment;
import zd.cornermemory.fragment.ReadCodeFragment;
import zd.cornermemory.fragment.RememberFragment;
import zd.cornermemory.fragment.SettingFragment;
import zd.cornermemory.fragment.TimerFragment;
import zd.cornermemory.utils.Configs;
import zd.cornermemory.utils.Dictionary;
import zd.cornermemory.utils.SPUtils;
import zd.cornermemory.utils.SpKey;
import zd.cornermemory.utils.Timer;

import static zd.cornermemory.utils.Configs.dip300;
import static zd.cornermemory.utils.Configs.fontScale;
import static zd.cornermemory.utils.Configs.scale;

/**
 * Created by zhud on 2019/4/29.
 */
public class MainActivity extends FragmentActivity implements OnClickListener {
    //五个Tab的布局文件
    private LinearLayout mTab1Layout;
    private LinearLayout mTab2Layout;
    private LinearLayout mTab3Layout;
    private LinearLayout mTab4Layout;
    private LinearLayout mTab5Layout;

    //五个Tab的ImageButton
    private ImageButton mTab1Img;
    private ImageButton mTab2Img;
    private ImageButton mTab3Img;
    private ImageButton mTab4img;
    private ImageButton mTab5Img;

    //五个Tab分别对应的Fragment
    private Fragment mFrag1;
    private Fragment mFrag2;
    private Fragment mFrag3;
    private Fragment mFrag4;
    private Fragment mFrag5;

    private TextView id_tab1_text;
    private TextView id_tab2_text;
    private TextView id_tab3_text;
    private TextView id_tab4_text;
    private TextView id_tab5_text;

    private   int            currentTab;//默认0
    public static DisplayMetrics dm;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        dm = getResources().getDisplayMetrics();
        Configs.width = dm.widthPixels;
        Configs.height = dm.heightPixels;
        scale = dm.density;
        fontScale = dm.scaledDensity;
        dip300 = (int) Math.round(scale * 250);
        currentTab = SPUtils.getInstance().getInt(SpKey.REMEMBER_TAB, 0);
        Dictionary.initDic();
        Dictionary.initPic();
        Dictionary.initFormulaCorner();
        Dictionary.initFormulaEdge();
        initViews();//初始化控件
        initEvents();//初始化事件
        selectTab(currentTab);
        SPUtils.getInstance().put(SpKey.IS_FIRST,false);//进来之后，设置为false

        PgyerSDKManager.checkVersionUpdate(MainActivity.this, new CheckoutCallBack() {
            @Override
            public void onNewVersionExist(final CheckSoftModel model) {
                //检查版本成功（有新版本）

                /**
                 *   CheckSoftModel 参数介绍
                 *
                 *    private int buildBuildVersion;//蒲公英生成的用于区分历史版本的build号
                 *     private String forceUpdateVersion;//强制更新版本号（未设置强置更新默认为空）
                 *     private String forceUpdateVersionNo;//强制更新的版本编号
                 *     private boolean needForceUpdate;//	是否强制更新
                 *     private boolean buildHaveNewVersion;//是否有新版本
                 *     private String downloadURL;//应用安装地址
                 *     private String buildVersionNo;//上传包的版本编号，默认为1 (即编译的版本号，一般来说，编译一次会
                 *    变动一次这个版本号, 在 Android 上叫 Version Code。对于 iOS 来说，是字符串类型；对于 Android 来
                 *    说是一个整数。例如：1001，28等。)
                 *     private String buildVersion;//版本号, 默认为1.0 (是应用向用户宣传时候用到的标识，例如：1.1、8.2.1等。)
                 *     private String buildShortcutUrl;//	应用短链接
                 *     private String buildUpdateDescription;//	应用更新说明
                 */
                new AlertDialog.Builder(MainActivity.this)
                        .setTitle(getString(R.string.found_new))
                        .setMessage(model.getBuildUpdateDescription())
                        .setCancelable(false)
                        .setNegativeButton(getString(R.string.cancel),null)
                        .setPositiveButton(getString(R.string.download), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(model.getBuildShortcutUrl()));
                                startActivity(intent);
                                dialog.dismiss();
                            }
                        }).show();

            }

            @Override
            public void onNonentityVersionExist(String string) {
                //无新版本
            }

            @Override
            public void onFail(String error) {
                //请求异常
            }
        });

    }

    private void initEvents() {
        //获取FragmentManager对象
        FragmentManager manager = getSupportFragmentManager();
//        //获取FragmentTransaction对象
        FragmentTransaction transaction = manager.beginTransaction();
        mFrag1 = new RememberFragment();
        mFrag2 = new ReadCodeFragment();
        mFrag3 = new DisruptFragment();
        mFrag4 = new TimerFragment();
        mFrag5 = new SettingFragment();

        transaction.add(R.id.id_content, mFrag1);
        transaction.add(R.id.id_content, mFrag2);
        transaction.add(R.id.id_content, mFrag3);
        transaction.add(R.id.id_content, mFrag4);
        transaction.add(R.id.id_content, mFrag5);
        transaction.commit();

        //初始化四个Tab的点击事件
        mTab1Layout.setOnClickListener(this);
        mTab2Layout.setOnClickListener(this);
        mTab3Layout.setOnClickListener(this);
        mTab5Layout.setOnClickListener(this);
        mTab4Layout.setOnClickListener(this);
    }

    private void initViews() {
        //初始化四个Tab的布局文件
        mTab1Layout = (LinearLayout) findViewById(R.id.id_tab_1);
        mTab2Layout = (LinearLayout) findViewById(R.id.id_tab_2);
        mTab3Layout = (LinearLayout) findViewById(R.id.id_tab_3);
        mTab4Layout = (LinearLayout) findViewById(R.id.id_tab_4);
        mTab5Layout = (LinearLayout) findViewById(R.id.id_tab_5);

        //初始化四个ImageButton
        mTab1Img = (ImageButton) findViewById(R.id.id_tab_1_img);
        mTab2Img = (ImageButton) findViewById(R.id.id_tab_2_img);
        mTab3Img = (ImageButton) findViewById(R.id.id_tab_3_img);
        mTab4img = (ImageButton) findViewById(R.id.id_tab_4_img);
        mTab5Img = (ImageButton) findViewById(R.id.id_tab_5_img);

        id_tab1_text = (TextView) findViewById(R.id.id_tab1_text);
        id_tab2_text = (TextView) findViewById(R.id.id_tab2_text);
        id_tab3_text = (TextView) findViewById(R.id.id_tab3_text);
        id_tab4_text = (TextView) findViewById(R.id.id_tab4_text);
        id_tab5_text = (TextView) findViewById(R.id.id_tab5_text);
    }

    //处理Tab的点击事件
    @Override
    public void onClick(View v) {

        if (mFrag4 != null&&(Timer.state == 1)) {
            return;
        }
        //先将四个ImageButton置为灰色
        resetImgs();
        try{
            InputMethodManager mInputMethodManager = (InputMethodManager)this.getSystemService(INPUT_METHOD_SERVICE);
            assert mInputMethodManager != null;
            mInputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);

        }catch (Exception e){

        }
        switch (v.getId()) {
            case R.id.id_tab_1:
                currentTab = 0;
                break;
            case R.id.id_tab_2:
                currentTab = 1;
                break;
            case R.id.id_tab_3:
                currentTab = 2;
                break;
            case R.id.id_tab_4:
                currentTab = 3;
                break;
            case R.id.id_tab_5:
                currentTab = 4;
                break;
        }
        selectTab(currentTab);
        SPUtils.getInstance().put(SpKey.REMEMBER_TAB,currentTab);
    }




    //进行选中Tab的处理
    private void selectTab(int i) {
        resetImgs();
        //获取FragmentManager对象
        FragmentManager manager = getSupportFragmentManager();
//        //获取FragmentTransaction对象
        FragmentTransaction transaction = manager.beginTransaction();
        //先隐藏所有的Fragment
        hideFragments(transaction);
        switch (i) {
            //当选中点击Tab时
            case 0:
                //设置ImageButton为选中
                mTab1Img.setImageResource(R.mipmap.tab1_pressed);
                id_tab1_text.setTextColor(getResources().getColor(R.color.white));
                transaction.show(mFrag1);

                break;
            case 1:
                mTab2Img.setImageResource(R.mipmap.tab2_pressed);
                id_tab2_text.setTextColor(getResources().getColor(R.color.white));
                transaction.show(mFrag2);
                break;
            case 2:
                mTab3Img.setImageResource(R.mipmap.tab3_pressed);
                id_tab3_text.setTextColor(getResources().getColor(R.color.white));
                transaction.show(mFrag3);

                break;
            case 3:
                mTab4img.setImageResource(R.mipmap.tab4_pressed);
                id_tab4_text.setTextColor(getResources().getColor(R.color.white));
                transaction.show(mFrag4);
                break;
            case 4:
                mTab5Img.setImageResource(R.mipmap.tab5_pressed);
                id_tab5_text.setTextColor(getResources().getColor(R.color.white));
                transaction.show(mFrag5);
                break;
        }
        //提交事务
        transaction.commit();
    }

    //将四个的Fragment隐藏
    private void hideFragments(FragmentTransaction transaction) {
        if (mFrag1 != null) {
            transaction.hide(mFrag1);
        }
        if (mFrag2 != null) {
            transaction.hide(mFrag2);
        }
        if (mFrag3 != null) {
            transaction.hide(mFrag3);
        }
        if (mFrag5 != null) {
            transaction.hide(mFrag5);
        }
        if (mFrag4 != null) {
            transaction.hide(mFrag4);
        }
    }

    //将四个ImageButton置为灰色
    private void resetImgs() {
        mTab1Img.setImageResource(R.mipmap.tab1_normal);
        mTab2Img.setImageResource(R.mipmap.tab2_normal);
        mTab3Img.setImageResource(R.mipmap.tab3_normal);
        mTab4img.setImageResource(R.mipmap.tab4_normal);
        mTab5Img.setImageResource(R.mipmap.tab5_normal);
        id_tab1_text.setTextColor(getResources().getColor(R.color.line));
        id_tab2_text.setTextColor(getResources().getColor(R.color.line));
        id_tab3_text.setTextColor(getResources().getColor(R.color.line));
        id_tab4_text.setTextColor(getResources().getColor(R.color.line));
        id_tab5_text.setTextColor(getResources().getColor(R.color.line));
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (null != this.getCurrentFocus()) {
            /**
             * 点击空白位置 隐藏软键盘
             */
            InputMethodManager mInputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
            assert mInputMethodManager != null;
            return mInputMethodManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
        }
        return super.onTouchEvent(event);
    }

    private long mExitTime;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //判断用户是否点击了“返回键”
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mFrag4 != null&&(Timer.state == 1)) {
                TimerFragment fragment = (TimerFragment) mFrag4;
                fragment.onKeyDown();
                return true;
            }

            //与上次点击返回键时刻作差
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                //大于2000ms则认为是误操作，使用Toast进行提示
                Toast.makeText(this, getString(R.string.next_eixt), Toast.LENGTH_SHORT).show();
                //并记录下本次点击“返回键”的时刻，以便下次进行判断
                mExitTime = System.currentTimeMillis();
            } else {
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}
